<template>
	<!-- 背景 -->
	<image class="bg-image" src='../../static/welcomeimg.png'></image>
	<view class="welcome-page">
		<!-- 头像 -->
		<view class="avatar-container" v-if="buttonText === '进入'">
			<button open-type="chooseAvatar" @chooseavatar="onChooseAvatar" class="avatar-button">
				<image class="avatar" :src="avatarUrl"></image>
			</button>
		</view>
		<view class="avatar-container" v-else>
			<image class="oldavatar" :src="avatarUrl"></image>
		</view>

		<!-- 用户名 -->
		<view class="username-container" v-if="buttonText === '进入'">
			<input class="username" v-model="nickname" type="nickname" placeholder="请输入昵称" @input="onNicknameInput"  />
			<image src="@/static/random.png" class="randomimg" @tap="randomNickname"
				:class="{ 'rotate': rotateButton }"></image>
		</view>
		<view class="username-container" v-else>
			<!-- 这里样式调整下 -->
			<text class="oldusername">{{ nickname }}</text>
		</view>

		<!-- 按钮 -->
		<view class="button-container">
			<button class="enter-button" @click="enterHandler">{{ buttonText }}</button>
		</view>
	</view>

	<!-- 调试 -->
	<view class="my">
		<button @tap="user.setUserInfo({ 
            avatar: 'http://yjy-xiaotuxian-dev.oss-cn-beijing.aliyuncs.com/picture/2021-04-06/db628d42-88a7-46e7-abb8-659448c33081.png',
            openid: 'oYo9u6yEshe2Np1yGlaxgezn6qo8',
            user_id: 2,
            username: '硬编码'
        })" size="mini" plain type="primary">
			保存用户信息
		</button>
		<button @tap="user.clearUserInfo()" size="mini" plain type="warn">
			清理用户信息
		</button>
	</view>
</template>

<script setup>
import {ref,onMounted} from 'vue';
import {onLoad} from '@dcloudio/uni-app';
import {userStore} from '@/stores/modules/user.js';
// 引入 multiavatar 库
import multiavatar from '@multiavatar/multiavatar';
import {get_openid} from '@/utils/api/login.js'
// 获取用户信息
const user = userStore();
// 定义响应式数据
const avatarUrl = ref('/static/user.png');
const nickname = ref('');
const buttonText = ref('进入');
const rotateButton = ref(false);
// 生命周期钩子
onLoad(() => {
	// 加载缓存
	getUserInfoFromCache();
});

	// 定义方法
	// 检查缓存
	// const getUserInfoFromCache = () => {
	//     const userinfo = JSON.parse(uni.getStorageSync('user')).userinfo;
	//     if (userinfo && userinfo.avatar && userinfo.username) {
	//         avatarUrl.value = userinfo.avatar;
	//         nickname.value = userinfo.username;
	//         buttonText.value = '欢迎回来';
	//     } else {
	// 		// 这里要做异常补货有问题的
	//         console.log("未找到用户信息或用户信息不完整");
	//     }
	// };



	const getUserInfoFromCache = () => {
		const userData = uni.getStorageSync('user');
		if (userData) {
			try {
				// console.log('解析前的userData:', userData);
				const userinfo = JSON.parse(userData).userinfo;
				if (userinfo && userinfo.avatar && userinfo.username) {
					avatarUrl.value = userinfo.avatar;
					// console.log('设置后的avatarUrl:', avatarUrl.value);
					nickname.value = userinfo.username;
					buttonText.value = '欢迎回来';
				} else {
					console.log("未找到用户信息或用户信息不完整");
				}
			} catch (error) {
				console.error('解析用户信息时出错:', error);
			}
		} else {
			console.log("本地存储中未找到用户信息");
		}
	};




	// 生成随机用户名
	const generateRandomUsername = () => {
		const adjectives = ['快乐的', '伤心的', '生气的', '聪明的', '勇敢的', '飞翔的'];
		const nouns = ['小丸子', '海芋', '格登', '饺子', '兔子', '子涵'];
		const randomAdjective = adjectives[Math.floor(Math.random() * adjectives.length)];
		const randomNoun = nouns[Math.floor(Math.random() * nouns.length)];
		// 生成三位随机数字编号
		// const randomNumber = Math.floor(Math.random() * 900) + 100;
		// return `${randomAdjective}${randomNoun}${randomNumber}`;
		return `${randomAdjective}${randomNoun}`;
	};
	// 生成随机用户头像
	// const generateRandomUser = async () => {
	//     const randomUsername = generateRandomUsername();
	//     // 使用 @multiavatar/multiavatar 库生成头像
	//     const avatarSvg = multiavatar(randomUsername);
	//     // 将生成的 SVG 数据转换为 base64 编码，以便在 image 元素中显示
	//     avatarUrl.value = `data:image/svg+xml;base64,${btoa(avatarSvg)}`;
	//     nickname.value = randomUsername;
	// };
	// 生成随机用户头像
	const generateRandomUser = async () => {
		const randomUsername = generateRandomUsername();
		// 使用 @multiavatar/multiavatar 库生成头像
		const avatarSvg = multiavatar(randomUsername);
		// 手动将字符串转换为 Uint8Array
		function stringToUint8Array(str) {
			const arr = [];
			for (let i = 0; i < str.length; i++) {
				const code = str.charCodeAt(i);
				if (code < 0x80) {
					arr.push(code);
				} else if (code < 0x800) {
					arr.push(0xc0 | (code >> 6));
					arr.push(0x80 | (code & 0x3f));
				} else if (code < 0xd800 || code >= 0xe000) {
					arr.push(0xe0 | (code >> 12));
					arr.push(0x80 | ((code >> 6) & 0x3f));
					arr.push(0x80 | (code & 0x3f));
				} else {
					i++;
					code = 0x10000 + (((code & 0x3ff) << 10) | (str.charCodeAt(i) & 0x3ff));
					arr.push(0xf0 | (code >> 18));
					arr.push(0x80 | ((code >> 12) & 0x3f));
					arr.push(0x80 | ((code >> 6) & 0x3f));
					arr.push(0x80 | (code & 0x3f));
				}
			}
			return new Uint8Array(arr);
		}
		const uint8Array = stringToUint8Array(avatarSvg);
		// 将 Uint8Array 转换为 ArrayBuffer
		const arrayBuffer = uint8Array.buffer;
		// 将 ArrayBuffer 转换为 Base64 编码
		const base64 = uni.arrayBufferToBase64(arrayBuffer);
		avatarUrl.value = `data:image/svg+xml;base64,${base64}`;
		// <img src=""/>
		nickname.value = randomUsername;
	};


	// 监测微信获取的头像用户名有没有更新到响应式数据
	const onChooseAvatar = (e) => {
		const {
			avatarUrl: newAvatarUrl
		} = e.detail;
		avatarUrl.value = newAvatarUrl;
		console.log('选择头像后的 avatarUrl:', avatarUrl.value);
	};
	const onNicknameInput = (e) => {
	    nickname.value = e.target.value;
	    console.log('输入用户名后的 nickname:', nickname.value);
	};
	
	
	
	
	// const registerandlogin = () => {
	// 	get_openid().then(res => {
	// 			user.setUserInfo(res);
	// 			uni.showToast({
	// 				icon: 'success',
	// 				title: '登录成功'
	// 			});
	// 			setTimeout(() => {
	// 				uni.switchTab({
	// 					url: '/pages/index/index'
	// 				});
	// 			}, 500);
	// 		})
	// 		.catch(error => {
	// 			console.error("发生错误:", error); // 捕获并打印任何发生的错误
	// 		});
	// };


	const enterHandler = async () => {
    if (buttonText.value === '欢迎回来') {
        uni.switchTab({
            url: '/pages/index/index'
        });
    } else {
        const isAvatarValid = avatarUrl.value && avatarUrl.value!== '/static/user.png';
        const isNicknameValid = nickname.value && nickname.value.trim()!== '';
		
        if (!isAvatarValid ||!isNicknameValid) {	
			await randomNickname();
            uni.showToast({
                title: '已设置随机信息',
                icon: 'none'
            });
			// console.log("avatarUrl.value",avatarUrl.value)
			// console.log("nickname.value",nickname.value)
   //          console.log('头像是否有效:', isAvatarValid);
   //          console.log('用户名是否有效:', isNicknameValid);
            // return;
        }

        get_openid()
         .then(async (res) => {
                if (res) {
                    const openid = res;
                    try {
                        const response = await uni.request({
                            url: '/minisoft/storeuserinfo',
                            method: 'post',
                            data: {
                                "openid": openid,
                                "name": nickname.value,
                                "avatar": avatarUrl.value
                            }
                        });
						
                        user.setUserInfo(response.data);
						
                        uni.showToast({
                            icon:'success',
                            title: '登录成功'
                        });
                        setTimeout(() => {
                            uni.switchTab({
                                url: '/pages/index/index'
                            });
                        }, 500);
                        console.log(response.data);
                        return response.data;
                    } catch (error) {
                        console.error('请求后端登录接口失败:', error);
                        uni.showToast({
                            icon: 'error',
                            title: '登录失败，请重试'
                        });
                        throw error;
                    }
                } else {
                    console.error('登录失败！' + res.errMsg);
                    uni.showToast({
                        icon: 'error',
                        title: '登录失败，请重试'
                    });
                    throw new Error(res.errMsg);
                }
            })
         .catch(error => {
                console.error("发生错误:", error);
                uni.showToast({
                    icon: 'error',
                    title: '登录失败，请重试'
                });
            });
    }
};

	const randomNickname = () => {
	    return new Promise((resolve) => {
	        rotateButton.value = true;
	        setTimeout(async () => {
	            rotateButton.value = false;
	            await generateRandomUser();
	            resolve(); // 通知外部可以继续
	        }, 600);
	    });
	};
</script>

<style>
	.bg-image {
		width: 100%;
		height: 100%;
		position: absolute;
		z-index: -1;
	}

	.welcome-page {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: flex-start;
		height: 90vh;
		position: relative;
		overflow: hidden;
	}

	.avatar-container {
		margin-top: 10vh;
		margin-bottom: 20px;
	}

	.avatar-button {
		width: 120px;
		height: 120px;
		border-radius: 50%;
		border: none;
		padding: 0;
		background-color: transparent;
	}

	.oldavatar {
		width: 120px;
		height: 120px;
		border-radius: 50%;
		border: none;
		padding: 0;
		background-color: transparent;
	}

	.avatar {
		width: 100%;
		height: 100%;
		border-radius: 50%;
	}

	.username-container {
		display: flex;
		margin-bottom: 20px;
		align-items: center;
		position: relative;
	}

	.username {
		left: 50%;
		font-size: 18px;
		color: #333;
		/* background-color:transparent; */
		/* 修改背景颜色为半透明 */
		background-color: rgba(255, 255, 255, 0.4);
		/* border: 1px solid rgba(255, 255, 255, 0.5); */
		border-radius: 50px;
		padding: 10px 20px;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		width: 200px;
		outline: none;
	}

	.oldusername {
		left: 50%;
		font-size: 25px;
		/* color: #333; */
		background-color: transparent;
		padding: 10px 20px;
		width: 200px;
		text-align: center;
		/* 实现文本水平居中 */
		display: flex;
		/* 使用 flexbox 布局 */
		justify-content: center;
		/* 水平居中 */
		align-items: center;
		/* 垂直居中 */
	}

	.enter-button {
		padding: 5px 20px;
		background-color: #007AFF;
		/* background-color:  rgba(48, 20, 29, 0.4); */
		color: white;
		border: none;
		border-radius: 50px;
		position: absolute;
		top: 80%;
		left: 50%;
		transform: translate(-50%, 50%);
	}

	.randomimg {
		width: 35px;
		height: 35px;
		object-fit: contain;
		/* padding-left: 10px; */
		position: absolute;
		right: 10px;
		top: 50%;
		transform: translateY(-50%);
		z-index: 3;
		/* 添加这一行 */

	}

	@keyframes rotate {
		from {
			transform: translateY(-50%) rotate(0deg);
			/* 确保旋转时垂直居中 */
		}

		to {
			transform: translateY(-50%) rotate(360deg);
			/* 确保旋转时垂直居中 */
		}
	}

	.rotate {
		animation: rotate 0.6s ease-in-out;
	}
</style>